package org.csu.onlineedubackend.controller;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.stp.StpUtil;
import org.csu.onlineedubackend.entity.FriendRelationship;
import org.csu.onlineedubackend.entity.FriendRequest;
import org.csu.onlineedubackend.entity.User;
import org.csu.onlineedubackend.result.CommonResponse;
import org.csu.onlineedubackend.service.FriendService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/friend")
public class FriendController {

    @Autowired
    private FriendService friendService;

    private Integer getUserIdFromRequest(HttpServletRequest request) throws NotLoginException {
        try {
            return StpUtil.getLoginIdAsInt();
        } catch (NotLoginException e) {
            String token = request.getHeader("satoken");
            if (token == null || token.isEmpty()) {
                token = request.getParameter("token");
            }

            if (token != null && !token.isEmpty()) {
                Object loginId = StpUtil.getLoginIdByToken(token);
                if (loginId != null) {
                    return Integer.parseInt(loginId.toString());
                }
            }
            throw new NotLoginException("未登录或登录已过期，请重新登录", e.getType(), e.getLoginType());
        }
    }

    /**
     * 发送好友申请
     */
    @PostMapping("/request")
    public CommonResponse<FriendRequest> sendFriendRequest(
            @RequestBody Map<String, Integer> requestBody,
            @RequestParam Integer userId) {
        Integer targetUserId = requestBody.get("targetUserId");
        if (targetUserId == null) {
            return CommonResponse.createForError("目标用户ID不能为空");
        }
        
        try {
            Integer currentUserId = userId;
            FriendRequest friendRequest = friendService.sendFriendRequest(currentUserId, targetUserId);
            return CommonResponse.createForSuccess(10000, "发送好友申请成功", friendRequest);
        } catch (NotLoginException e) {
            return CommonResponse.createForError(e.getMessage());
        } catch (RuntimeException e) {
            return CommonResponse.createForError(e.getMessage());
        }
    }
    
    /**
     * 接受好友申请
     */
    @PostMapping("/accept/{requestId}")
    public CommonResponse<FriendRelationship> acceptFriendRequest(@PathVariable Long requestId,
                                                                  @RequestParam Integer userId) {
        try {
            Integer currentUserId = userId;
            FriendRelationship relationship = friendService.acceptFriendRequest(requestId, currentUserId);
            return CommonResponse.createForSuccess(10000, "接受好友申请成功", relationship);
        } catch (NotLoginException e) {
            return CommonResponse.createForError(e.getMessage());
        } catch (RuntimeException e) {
            return CommonResponse.createForError(e.getMessage());
        }
    }
    
    /**
     * 拒绝好友申请
     */
    @PostMapping("/reject/{requestId}")
    public CommonResponse<FriendRequest> rejectFriendRequest(@PathVariable Long requestId, HttpServletRequest request) {
        try {
            Integer currentUserId = getUserIdFromRequest(request);
            FriendRequest friendRequest = friendService.rejectFriendRequest(requestId, currentUserId);
            return CommonResponse.createForSuccess(10000, "拒绝好友申请成功", friendRequest);
        } catch (NotLoginException e) {
            return CommonResponse.createForError(e.getMessage());
        } catch (RuntimeException e) {
            return CommonResponse.createForError(e.getMessage());
        }
    }
    
    /**
     * 获取收到的好友申请
     */
    @GetMapping("/requests/received")
    public CommonResponse<List<FriendRequest>> getReceivedFriendRequests(HttpServletRequest request) {
        try {
            Integer currentUserId = getUserIdFromRequest(request);
            List<FriendRequest> requests = friendService.getAllFriendRequests(currentUserId);
            return CommonResponse.createForSuccess(10000, "获取收到的好友申请成功", requests);
        } catch (NotLoginException e) {
            return CommonResponse.createForError(e.getMessage());
        }
    }
    
    /**
     * 获取发送的好友申请
     */
    @GetMapping("/requests/sent")
    public CommonResponse<List<FriendRequest>> getSentFriendRequests(HttpServletRequest request) {
        try {
            Integer currentUserId = getUserIdFromRequest(request);
            List<FriendRequest> requests = friendService.getSentFriendRequests(currentUserId);
            return CommonResponse.createForSuccess(10000, "获取发送的好友申请成功", requests);
        } catch (NotLoginException e) {
            return CommonResponse.createForError(e.getMessage());
        }
    }
    
    /**
     * 获取好友列表
     */
//    @GetMapping("/list")
//    public CommonResponse<List<User>> getFriendList(HttpServletRequest request) {
//        try {
//            Integer currentUserId = getUserIdFromRequest(request);
//            List<User> friends = friendService.getFriendList(currentUserId);
//            return CommonResponse.createForSuccess(10000, "获取好友列表成功", friends);
//        } catch (NotLoginException e) {
//            return CommonResponse.createForError(e.getMessage());
//        }
//    }

    @GetMapping("/list")
    public CommonResponse<List<User>> getFriendList(
            @RequestParam Integer userId  // 直接从URL参数获取
    ) {
        try {
            List<User> friends = friendService.getFriendList(userId); // 使用前端传入的ID
            return CommonResponse.createForSuccess(10000, "获取好友列表成功", friends);
        } catch (Exception e) {
            return CommonResponse.createForError(e.getMessage());
        }
    }
    
    /**
     * 删除好友
     */
    @DeleteMapping("/{friendId}")
    public CommonResponse<Boolean> deleteFriend(@PathVariable Integer friendId,
                                                @RequestParam Integer userId) {
        try {
            Integer currentUserId = userId;
            boolean result = friendService.deleteFriend(currentUserId, friendId);
            return CommonResponse.createForSuccess(10000, "删除好友成功", result);
        } catch (NotLoginException e) {
            return CommonResponse.createForError(e.getMessage());
        } catch (RuntimeException e) {
            return CommonResponse.createForError(e.getMessage());
        }
    }
    
    /**
     * 搜索用户
     */
    @GetMapping("/search")
    public CommonResponse<List<User>> searchUsers(@RequestParam String keyword, HttpServletRequest request) {
        try {
            getUserIdFromRequest(request); // Check login status
            List<User> users = friendService.searchUsers(keyword);
            return CommonResponse.createForSuccess(10000, "搜索用户成功", users);
        } catch (NotLoginException e) {
            return CommonResponse.createForError(e.getMessage());
        }
    }
    
    /**
     * 检查是否是好友
     */
    @GetMapping("/check/{userId}")
    public CommonResponse<Boolean> checkFriendship(@PathVariable Integer userId, HttpServletRequest request) {
        try {
            Integer currentUserId = getUserIdFromRequest(request);
            boolean areFriends = friendService.areFriends(currentUserId, userId);
            return CommonResponse.createForSuccess(10000, "检查好友关系成功", areFriends);
        } catch (NotLoginException e) {
            return CommonResponse.createForError(e.getMessage());
        }
    }
    
    /**
     * 从通知接受好友申请
     */
    @PostMapping("/request/accept-from-notification")
    public CommonResponse<FriendRelationship> acceptFriendRequestFromNotification(@RequestBody Map<String, Object> requestBody,
                                                                                  @RequestParam Integer userId) {
        Integer senderId = (Integer) requestBody.get("senderId");
        Long notificationId = Long.valueOf(requestBody.get("notificationId").toString());
        
        if (senderId == null) {
            return CommonResponse.createForError("发送者ID不能为空");
        }
        
        try {
            Integer currentUserId = userId;
            FriendRelationship relationship = friendService.acceptFriendRequestFromNotification(senderId, currentUserId, notificationId);
            return CommonResponse.createForSuccess(10000, "接受好友申请成功", relationship);
        } catch (NotLoginException e) {
            return CommonResponse.createForError(e.getMessage());
        } catch (RuntimeException e) {
            return CommonResponse.createForError(e.getMessage());
        }
    }
    
    /**
     * 从通知拒绝好友申请
     */
    @PostMapping("/request/reject-from-notification")
    public CommonResponse<Boolean> rejectFriendRequestFromNotification(@RequestBody Map<String, Object> requestBody,
                                                                       @RequestParam Integer userId) {
        Integer senderId = (Integer) requestBody.get("senderId");
        Long notificationId = Long.valueOf(requestBody.get("notificationId").toString());
        
        if (senderId == null) {
            return CommonResponse.createForError("发送者ID不能为空");
        }
        
        try {
            Integer currentUserId = userId;
            boolean result = friendService.rejectFriendRequestFromNotification(senderId, currentUserId, notificationId);
            return CommonResponse.createForSuccess(10000, "拒绝好友申请成功", result);
        } catch (NotLoginException e) {
            return CommonResponse.createForError(e.getMessage());
        } catch (RuntimeException e) {
            return CommonResponse.createForError(e.getMessage());
        }
    }
} 